package com.online_video.servlet.admin;

import com.google.gson.Gson;
import com.online_video.entity.Page;
import com.online_video.entity.User;
import com.online_video.entity.Video;
import com.online_video.entity.VideoPage;
import com.online_video.service.UserService;
import com.online_video.service.VideoService;
import com.online_video.service.impl.UserServiceImpl;
import com.online_video.service.impl.VideoServiceImpl;
import com.online_video.servlet.BaseServlet;
import com.online_video.utils.GetMD5;
import com.online_video.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author zhenghouwen
 * @create 2022-03-14 14:12
 */
//
@WebServlet("/admin/admin.do")
public class AdminServlet extends BaseServlet {
    UserService userService = new UserServiceImpl();
    VideoService videoService = new VideoServiceImpl();
    public void queryAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<User> users = userService.queryAllUser();
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(new Gson().toJson(users));
    }
//添加新用户
    public void register(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = GetMD5.string2MD5(request.getParameter("password"));
        String nickname = request.getParameter("nickname");
        String telephone = request.getParameter("telephone");
        String email = request.getParameter("email");
        String sex = request.getParameter("sex");
        User user = new User(null, 1, username, password, nickname, sex, telephone, email, null, null, 1, 0);
        int register = userService.register(user);
        if (register > 0) {
            Gson gson = new Gson();
            String str = "注册成功";
            String jsonStr = "{key'添加新用户'}";
            response.getWriter().write(jsonStr);
        }
    }
    //删除用户
    public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Integer id = Integer.parseInt(request.getParameter("id"));
        int isDel = userService.deleteUserById(id);
        if (isDel>0){
            String toJson = new Gson().toJson("1");
            response.getWriter().write(toJson);
        }
    }
    //修改用户
    public void update(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        Integer id = Integer.parseInt(request.getParameter("id"));
        User user = userService.queryByU_id(id);
        String isActive1 = request.getParameter("isActive");
        if (isActive1!=null&&!"".equals(isActive1)){
            Integer isActive = Integer.parseInt(isActive1);
            if (isActive != null && id != null){
                user.setIsactive(isActive);
                int insert = userService.update(user);
                /*信息更新成功*/
                if (insert>0){
                    String toJson = new Gson().toJson("1");
                    response.getWriter().write(toJson);
                    /*单独修改用户状态 到此返回 函数结束*/
                    return;
                }
            }
        }

        String userName = request.getParameter("userName");
        String nickName = request.getParameter("nickName");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        Integer isVip = Integer.parseInt(request.getParameter("isVip"));


        if (userName!=null&&nickName!=null&&email!=null&&phone!=null&&isVip!=null&&!"".equals(userName)&&!"".equals(nickName)&&!"".equals(email)&&!"".equals(phone)){
            user.setUsername(userName);
            user.setNickname(nickName);
            user.setEmail(email);
            user.setTelephone(phone);
            user.setIsvip(isVip);
            int update = userService.update(user);
            if (update>0){
                String toJson = new Gson().toJson("1");
                response.getWriter().write(toJson);
            }else {
                String toJson = new Gson().toJson("0");
                response.getWriter().write(toJson);
            }

        }else {
            String toJson = new Gson().toJson("-1");
            response.getWriter().write(toJson);
        }




    }
    /*用户信息分页显示*/
    public void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer start = WebUtils.parseInt(request.getParameter("pageNo"),1);
        Integer pageSize =  WebUtils.parseInt(request.getParameter("pageSize"),Page.DEFAULT_PAGE_SIZE);
        Page<User> page = userService.page(start, pageSize);
        request.setAttribute("userPage",page);
        request.getRequestDispatcher("/admin/user_info.jsp").forward(request,response);
    }
    /*根据id查找用户信息*/
    public void queryByid(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Integer id = Integer.parseInt(request.getParameter("id"));
        User user = userService.queryByU_id(id);
        if (user!=null){
            String toJson = new Gson().toJson(user);
            response.getWriter().write(toJson);
        }
    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Cookie usernameCookie;
        Cookie passwordCookie;
        String username = request.getParameter("username");
        String remeberMe = request.getParameter("remeberMe");
        String password = "";
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if ("password".equals(cookie.getName())) {
                password = cookie.getValue();
                break;
            } else {
                password = GetMD5.string2MD5(request.getParameter("password"));
            }
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        User login = userService.login(user);
        if (login != null) {
            //登录成功
            //记住我
            if ("remember-me".equals(remeberMe)) {
                usernameCookie = new Cookie("username", username);
                passwordCookie = new Cookie("password", password);
                usernameCookie.setMaxAge(60 * 60 * 24 * 7);
                passwordCookie.setMaxAge(60 * 60 * 24 * 7);
                response.addCookie(usernameCookie);
                response.addCookie(passwordCookie);

                HttpSession session = request.getSession();
                session.setMaxInactiveInterval(60 * 60 * 24);
                session.setAttribute("user", login);
                request.getRequestDispatcher("./index.jsp").forward(request, response);

            } else {
                usernameCookie = new Cookie("username", username);
                passwordCookie = new Cookie("password", password);
                usernameCookie.setMaxAge(0);
                passwordCookie.setMaxAge(0);
                response.addCookie(usernameCookie);
                response.addCookie(passwordCookie);

                HttpSession session = request.getSession();
                response.sendRedirect("./index.jsp");
            }
        } else {
            //登录失败
            request.setAttribute("code", "-1");
            request.getRequestDispatcher("./login.jsp").forward(request, response);
        }
    }

    /**
     * 视频页面分页显示
     * @param request
     * @param response
     */
    public void videoPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), VideoPage.DEFAULT_PAGE_SIZE);
        VideoPage<Video> page = videoService.page(pageNo, pageSize, "", "");
        request.setAttribute("video",page);
        request.getRequestDispatcher("./video_info.jsp").forward(request,response);

    }
}
